'use strict';
import React, {
    Component
} from 'react'
import {
    HttpService,
    Tips,
    getLocalTime,
    urlKey,
    pullDownRefresh,
    sxtUrl
} from '../Tools'
import {
    Link,
    hashHistory
} from 'react-router'
import $ from 'jquery'
import QueueAnim from 'rc-queue-anim';
import Header from './Common/Header'
import LoadingBox from './Common/LoadingBox'
import '../Plugins/banner/css/banner.css'
import '../Plugins/banner/js/banner.js'
import '../Plugins/swiper/css/swiper.min.css'
import '../Plugins/swiper/js/swiper.jquery.min.js'

import imgBanner from '../Img/info/banner.png'
import imgDetail from '../Img/info/detail.png'
import imgTop from '../Img/info/top.png'
import splitGraphBig from '../Img/other/splitGraphBig.png'

export default class Info extends Component {
    constructor(props) {
        super(props)
        this.page = 1;
        this.pagesize = 10;
        this.toBottom = 60;
        this.allDataList = [];
        this.state = {
            dataList: [],
            articleType: [],
            bannerList: [],
            bannerUrlFirst: imgBanner,
            dataLoad: 1,
            dataEnd: 0,
            dataNull: 0
        }
        this.wherefrom = 'share'
        if (sessionStorage.app == 'true')
            this.wherefrom = 'app'
        if (sessionStorage.weixin == 'true')
            this.wherefrom = 'weixin'
    }
    componentWillUnmount() {
        clearInterval(sessionStorage.timer);
    }
    componentWillMount() {
        clearInterval(sessionStorage.timer);
        if (!sessionStorage.artIndex) {
            sessionStorage.artIndex = 0;
        }
        this.getArticleType()
        this.getBanner()
    }

    componentDidMount() {
        //APP底部处理
        if (this.wherefrom == 'app') {
            if (sessionStorage.wherefrom == 'ios') {
                if (window.webkit)
                    webkit.messageHandlers.bottomBar.postMessage(1);
            } else {
                if (window.appweb && window.appweb.bottomBar)
                    appweb.bottomBar(1)
            }
        }
        //加载更多
        window.onscroll = () => {
            const {
                dataEnd,
                dataNull
            } = this.state;
            if (this.dataLoad == 1 || dataEnd == 1 || dataNull == 1)
                return;
            var scrollTop = 0;
            if (document.documentElement && document.documentElement.scrollTop) {
                scrollTop = document.documentElement.scrollTop;
            } else if (document.body) {
                scrollTop = document.body.scrollTop;
            }
            if (document.body.clientHeight - window.innerHeight - scrollTop <= this.toBottom) {
                this.page++;
                this.getData();
            }
        }
        const obj = document.getElementById('refreshbox')
        const contentObj = document.getElementById('pdownrefresh')
        const statusObj = document.getElementById('status')
        pullDownRefresh(obj, contentObj, statusObj, 100, function(data) {
            if (data.status == 'end' && data.top >= 100 - 20) {
                this.getArticleType()
                this.getBanner(1)
            }
        }.bind(this))
    }

    //切换类型
    sltType(index, id) {
        sessionStorage.artIndex = index;
        sessionStorage.artTypeId = id;
        document.querySelector('.type .active').className = 'item';
        let obj = document.querySelectorAll('.type .item')[index];
        obj.className = 'item active';
        console.log('资讯-' + obj.innerText);
        _hmt.push(['_trackEvent', 'page', 'Info', '资讯-' + obj.innerText]);
        this.getData(1);
    }

    //读取状态
    readStatus(id) {
        if (localStorage.inforeadID) {
            if (localStorage.inforeadID.indexOf(id) == -1) {
                localStorage.inforeadID += id + ','
            }
        } else {
            localStorage.inforeadID = id + ','
        }
    }
    //获取数据列表
    getData(status) {
        this.dataLoad = 1
        this.setState({
            dataLoad: 1,
            dataEnd: 0,
            dataNull: 0
        });
        if (status == 1)
            this.page = 1
        let rct = this;
        $.ajax({
            url: sxtUrl + '/article/listArticleByTag',
            data: `tagId=${sessionStorage.artTypeId}&page=${this.page}&size=${this.pagesize}`,
            success: function(res) {
                rct.dataLoad = 0
                rct.setState({
                    dataLoad: 0
                });
                if (res.code == 50006) {
                    //获取数据成功
                    let dataList = res.data.list
                    if (status != 1)
                        dataList = rct.state.dataList.concat(res.data.list);
                    rct.setState({
                        dataList
                    });
                    if (res.data.total == rct.pagesize) {
                        rct.setState({
                            dataEnd: 1
                        });
                    } else if (res.data.list.length < rct.pagesize) {
                        rct.setState({
                            dataEnd: 1
                        });
                        if (dataList.length == 0) {
                            rct.setState({
                                dataEnd: 0
                                // dataNull: 1
                            });
                        }
                    }
                    return;
                }
                Tips(res.msg);
            },
            error: function() {
                Tips('网络连接失败')
            }
        })
    }
    //获取文章类型
    getArticleType() {
        let rct = this;
        $.get(sxtUrl + '/tag/listTag', function(res) {
            if (res.code == 50006) {
                if (res.data.length == 0) {
                    rct.setState({
                        dataLoad: 0
                        // dataNull: 1
                    });
                    return
                }
                res.data.unshift({
                    createTime: 1508121720000,
                    del: 0,
                    id: '',
                    pIndex: 2,
                    tagname: "热点",
                    userId: 1
                })
                sessionStorage.artTypeId = res.data[sessionStorage.artIndex].id
                rct.setState({
                    articleType: res.data
                })
                rct.getData(1);
                var swiper = new Swiper('.infotypelists', {
                    slidesPerView: res.data.length > 5 ? 5 : res.data.length,
                    paginationClickable: true,
                });
            } else {
                Tips(res.msg)
                rct.setState({
                    dataLoad: 0
                    // dataNull: 1
                });
            }
        });
    }
    //获取banner数据
    getBanner(status) {
        let rct = this;
        $.ajax({
            url: sxtUrl + '/banner/listBanner',
            success: function(res) {
                if (res.code == 10140) {
                    if (res.data.length == 0) {
                        $('.banner .position').css('opacity', 1)
                        return
                    }
                    if (res.data.length == 1) {
                        let item = res.data[0];
                        $('.banner .position').attr('src', item.bannerUrl).css('opacity', 1).click(function() {
                            let tolink = `/InfoDetail/${item.id}/${this.wherefrom}/banner`
                            if (item.displayType == 2 && item.displayContent)
                                tolink = `/iframe/share/${encodeURIComponent(item.theme)}/${encodeURIComponent(item.displayContent)}`
                            hashHistory.push(tolink)
                        })
                        return
                    }
                    rct.setState({
                        bannerList: res.data
                    })
                    //添加序号
                    $('.banner .status').empty();
                    for (var i = 1; i <= $('.banner li').length; i++) {
                        $('.banner .status').append('<a></a>');
                    }
                    //调用轮播
                    if (status != 1)
                        $(".imgs").touchSlider({
                            flexible: true,
                            speed: 500,
                            btn_prev: $(".btn_prev"),
                            btn_next: $(".btn_next"),
                            paging: $(".status a"),
                            counter: function(e) {
                                $(".status a").removeClass("active").eq(e.current - 1).addClass("active");
                            }
                        });

                    //自动滚动
                    clearInterval(sessionStorage.timer);
                    sessionStorage.timer = setInterval(() => {
                        $(".btn_next").click();
                    }, 5000);
                    //滑动事件关闭定时器
                    $(".banner").bind("touchstart", function() {
                        clearInterval(sessionStorage.timer);
                    }).bind("touchend", function() {
                        clearInterval(sessionStorage.timer);
                        sessionStorage.timer = setInterval(function() {
                            $(".btn_next").click();
                        }, 5000);
                    });
                } else {
                    Tips(res.msg)
                    $('.banner .position').css('opacity', 1)
                }
            }
        })
    }

    /**
     *
     * @param e htmlEelement
     */
    errorBannerImg(e) {
        e.target.src = splitGraphBig;
    }
    render() {
        const {
            dataLoad,
            articleType,
            bannerList,
            bannerUrlFirst,
            dataEnd,
            dataNull,
            dataList
        } = this.state;
        const dataTagList = dataList.map((item, index) => {
            const tolink = `/InfoDetail/${item.id}/${this.wherefrom}`
            let ready = '';
            if (localStorage.inforeadID && localStorage.inforeadID.indexOf(item.id) > -1)
                ready = 'ready'
            return (
                <li key={index+1} onClick={this.readStatus.bind(this,item.id)} className={ready}>
                    <div className='info'>
                        <Link className='title' to={tolink}>{item.up==0?null:<i></i>}{item.title}</Link>
                        <p className='time'><span dangerouslySetInnerHTML={{__html: item.createTime==null?'':getLocalTime(item.createTime).replace(/\./g,'-').replace(/ /g,'&nbsp;&nbsp;')}}></span><span>{item.readCount==0?null:`${item.readCount}阅`}</span></p>
                    </div>
                    <Link className='img' to={tolink} style={{backgroundImage:`url(${item.litimg})`}}></Link>
                </li>)
        });
        const artTypeTagList = articleType.map((item, index) => {
            let clsName = 'swiper-slide item';
            if (sessionStorage.artIndex == index)
                clsName += ' active';
            return (
                <Link onClick={this.sltType.bind(this,index,item.id)} className={clsName}>{item.tagname}</Link>
            )
        });
        const bannerTagList = bannerList.map((item, index) => {
            let tolink = `/InfoDetail/${item.id}/${this.wherefrom}/banner`
            if (item.displayType == 2 && item.displayContent)
                tolink = `/iframe/share/${encodeURIComponent(item.theme)}/${encodeURIComponent(item.displayContent)}`

            return (
                <li>
                    <Link to={tolink}>
                        <img src={item.bannerUrl} onError={this.errorBannerImg.bind(this)} />
                    </Link>
                </li>
            )
        });
        return (
            <div className='pjb_info'>
                <Header title='资讯'  noBack={sessionStorage.app=='true'&&sessionStorage.appback!=2?'1':null} outLink={sessionStorage.wherefrom=='ios'?'appback':null} />
                <div id='refreshbox'>
                    <div id='status'><span></span></div>
                    <div id='pdownrefresh'>
                        <div className="banner">
                            <div className="status"></div>
                            <div className="imgs">
                                <img src={bannerUrlFirst} className="position" />
                                <ul>
                                    {bannerTagList}
                                </ul>
                                <a className="btncommon btn_prev"></a>
                                <a className="btncommon btn_next"></a>
                            </div>
                        </div>
                        <div className='type clearfix infotypelists'>
                            <div className="swiper-wrapper">
                                {artTypeTagList}
                            </div>
                        </div>



                        {dataList.length>0?<div className='newsbox'>
                            <ul className='newslist'>
                                <QueueAnim
                                  animConfig={[
                                    { opacity: [1, 0], translateY: [0, 50] },
                                    { opacity: [1, 0], translateY: [0, -50] }
                                  ]}>
                                {dataTagList}
                                </QueueAnim>
                            </ul>
                        </div>:null}
                        <LoadingBox dataLoad={dataLoad} dataNull={dataNull} dataEnd={dataEnd}/>
                    </div>
                </div>
            </div>
        )
    }
}
